package com.kfit.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity //启用Spring Security.

////会拦截注解了@PreAuthrize注解的配置.
//@EnableGlobalMethodSecurity(securedEnabled=true)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	
	/**
	 * 通过复写configure方法，进行创建用户。
	 */
//	@Override
//	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		/*
//		 * 基于内存的方式，构建两个用户账号：admin/123456、user/123456
//		 */
//		auth.inMemoryAuthentication()
//			.withUser("admin")
//			.password(passwordEncoder().encode("123456"))
//			.roles("admin");
//		
//		
//		auth.inMemoryAuthentication()
//			.withUser("user")
//			.password(passwordEncoder().encode("123456"))
//			.roles("normal");
//	} 
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.
			formLogin().loginPage("/login")
			.and()
			.authorizeRequests()
			.antMatchers("/login").permitAll() //允许所有人可以访问登录页面.
			.antMatchers("/","/index").permitAll()
			.antMatchers("/test/**","/test1/**").permitAll()
			.antMatchers("/res/**/*.{js,html}").permitAll()//这个允许/res下.js和.html文件可以直接访问。
			//.anyRequest().access("@authService.canAccess(request,authentication)")
			.and().sessionManagement().maximumSessions(1)
			//.anyRequest().authenticated() // 所有的请求需要在登录之后才能够访问。
			
			;//配置登录页面
		
		
//		http.addFilterBefore(new BeforeLoginFilter(), UsernamePasswordAuthenticationFilter.class);
//		http.addFilterAfter(new AfterLoginFilter(), UsernamePasswordAuthenticationFilter.class);
//		http.addFilterAt(new AtLoginFilter(), UsernamePasswordAuthenticationFilter.class);
	}
	
	@Bean //注入PsswordEncoder
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
}
